import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout/Layout.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        component: () => import('@/views/index.vue')
      },
      {
        path: '/anime',
        component: () => import('@/views/anime/index.vue')
      },
      {
        path: '/article',
        component: () => import('@/views/article/index.vue')
      },
      {
        path: '/vipShop',
        component: () => import('@/views/vipShop/index.vue')
      },
      {
        path: '/message',
        component: () => import('@/views/message/index.vue')
      },
      {
        path: '/collection',
        component: () => import('@/views/collection/index.vue')
      },
      {
        path: '/vip',
        component: () => import('@/views/vip/index.vue')
      },
      {
        path: '/submissionVideo/:id',
        component: () => import('@/views/submission/video.vue')
      },
      {
        path: '/submissionArticle',
        component: () => import('@/views/submission/article.vue')
      },
      {
        path: '/searchVideo/:searchText',
        component: () => import('@/views/searchVideo/index.vue')
      },
      {
        path: '/video/:id',
        component: () => import('@/views/watch/index.vue')
      },
      {
        path: '/article/:id',
        component: () => import('@/views/watch/watchArticle.vue')
      },
      {
        path: '/submissionAnime',
        component: () => import('@/views/submission/anime.vue')
      },
      {
        path: '/user',
        component: () => import('@/views/user/index.vue')
      },
      {
        path: '/user/follow',
        component: () => import('@/views/user/follow.vue')
      },
      {
        path: '/hotVideo',
        component: () => import('@/views/hotVideo/index.vue')
      },
      {
        path: '/channelVideo/:id',
        component: () => import('@/views/channelVideo/index.vue')
      },
      {
        path: '/platform',
        component: () => import('@/views/platform/index.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 登录访问拦截
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  // if (!token && (to.path !== '/login' && to.path !== '/' && to.path !== '/vipShop' && to.path !== '/article' && to.path !== '/anime')) {
  //   next('/login')
  // }
  if (!token && to.path !== '/login') {
    next('/login')
  }
  next()
})

// 防止连续点击多次路由报错
const routerPush = VueRouter.prototype.push
const routerReplace = VueRouter.prototype.replace
// push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(err => err)
}
// replace
VueRouter.prototype.replace = function push (location) {
  return routerReplace.call(this, location).catch(err => err)
}

export default router
